import { api } from 'src/boot/axios'

import { useAuthStore } from 'src/stores/authStore'
import { storeToRefs } from 'pinia'
import { Notify } from 'quasar'

const { token } = storeToRefs(useAuthStore())

api.interceptors.request.use((request) => {
  request.headers.Authorization = token.value
  return request
})

api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    const response = error.response
    const result = response.data

    if (response.status === 401) {
      useAuthStore().removeToken()
    }

    Notify.create({
      message: result.message,
      color: 'negative',
      position: 'top',
      timeout: 1000,
    })
    return Promise.reject(error)
  }
)

export async function loginAPI(username: string, password: string) {
  const response = await api.post(
    `/user/login?username=${username}&password=${password}`
  )
  useAuthStore().setToken(response.headers['authorization'])
  return response.data.data
}

export async function deleteImage(imageUrl: string) {
  const response = await api.post(`/note/deleteImage?imageUrl=${imageUrl}`)
  return response.data.data
}
export interface NoteDTO {
  title: string
  description: string
  images: string[]
}
export async function publishAPI(noteDTO: NoteDTO) {
  const response = await api.post('/note/publish', noteDTO)
  return response.data.data
}

export async function getAllNotes() {
  const response = await api.get('/note/getAll')
  return response.data.data
}

export async function getNoteImages(noteId: number) {
  const response = await api.get('/note/getImages?noteId=' + noteId)
  return response.data.data
}

export async function getComments(noteId: number) {
  const response = await api.get('/note/getComments?noteId=' + noteId)
  return response.data.data
}

export interface NoteCommentDTO {
  parentId: number
  noteId: number
  content: string
}

export async function commentAPI(noteCommentDTO: NoteCommentDTO) {
  const response = await api.post('/note/comment', noteCommentDTO)
  return response.data.data
}
